import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "qrc:/qml/components" as Components
import "qrc:/qml/styles" as Styles

/**
 * @brief 仿真任务面板
 * @details 用于SimulatorScreen侧边栏，展示和发布仿真任务
 */
Rectangle {
    id: root
    color: Styles.Theme.surface

    // 外部接口
    property var taskListModel: null
    property string selectedChainId: ""

    signal taskSelected(string chainId)
    signal createTaskRequested()
    signal pauseTaskRequested(string chainId)
    signal resumeTaskRequested(string chainId)
    signal cancelTaskRequested(string chainId)

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: Styles.Theme.spacingNormal
        spacing: Styles.Theme.spacingSmall

        // ==================== 标题栏 ====================
        RowLayout {
            Layout.fillWidth: true
            spacing: Styles.Theme.spacingSmall

            Text {
                text: qsTr("仿真任务")
                color: Styles.Theme.textPrimary
                font.pixelSize: Styles.Theme.fontSizeLarge
                font.weight: Font.Bold
                Layout.fillWidth: true
            }

            // 快速统计
            Rectangle {
                Layout.preferredWidth: 60
                Layout.preferredHeight: 28
                radius: 14
                color: Styles.Theme.backgroundAlternate
                border.color: Styles.Theme.border
                border.width: 1

                RowLayout {
                    anchors.centerIn: parent
                    spacing: 4

                    Text {
                        text: qsTr("活跃")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: 10
                    }

                    Text {
                        text: getActiveTaskCount()
                        color: Styles.Theme.info
                        font.pixelSize: 12
                        font.weight: Font.Bold
                    }
                }
            }
        }

        // ==================== 任务筛选 ====================
        RowLayout {
            Layout.fillWidth: true
            spacing: Styles.Theme.spacingSmall

            // 状态筛选
            Components.CustomComboBox {
                id: statusFilter
                Layout.preferredWidth: 100
                model: [qsTr("全部"), qsTr("执行中"), qsTr("待处理"), qsTr("已完成"), qsTr("失败")]
                currentIndex: 0
            }

            Item {
                Layout.fillWidth: true
            }

            // 新建任务按钮
            Components.ActionButton {
                text: qsTr("+ 新建")
                buttonType: "primary"
                height: 32
                onClicked: createTaskRequested()
            }
        }

        // ==================== 任务操作按钮 ====================
        RowLayout {
            Layout.fillWidth: true
            spacing: Styles.Theme.spacingSmall

            Text {
                Layout.fillWidth: true
                text: selectedChainId.length > 0
                      ? qsTr("当前选中任务: %1").arg(selectedChainId)
                      : qsTr("请选择任务以执行操作")
                color: selectedChainId.length > 0 ? Styles.Theme.textSecondary : Styles.Theme.textDisabled
                font.pixelSize: Styles.Theme.fontSizeSmall
            }

            Components.ActionButton {
                text: qsTr("暂停")
                buttonType: "secondary"
                enabled: selectedChainId.length > 0
                onClicked: pauseTaskRequested(selectedChainId)
            }

            Components.ActionButton {
                text: qsTr("恢复")
                buttonType: "secondary"
                enabled: selectedChainId.length > 0
                onClicked: resumeTaskRequested(selectedChainId)
            }

            Components.ActionButton {
                text: qsTr("取消")
                buttonType: "danger"
                enabled: selectedChainId.length > 0
                onClicked: cancelTaskRequested(selectedChainId)
            }
        }

        // ==================== 任务列表 ====================
        ScrollView {
            Layout.fillWidth: true
            Layout.fillHeight: true
            clip: true

            ListView {
                id: taskListView
                model: taskListModel
                spacing: Styles.Theme.spacingSmall

                delegate: Components.TaskListCard {
                    width: taskListView.width
                    chainId: model.chainId
                    taskName: model.taskName || model.chainId
                    agvNumber: model.agvNumber
                    agvName: model.agvName
                    status: model.status
                    statusDisplay: model.statusDisplay
                    currentTaskIndex: model.currentTaskIndex
                    totalTasks: model.totalTasks
                    progress: model.progress

                    onClicked: {
                        root.selectedChainId = model.chainId
                        taskSelected(model.chainId)
                    }
                }

                // 空状态提示
                Label {
                    visible: taskListView.count === 0
                    anchors.centerIn: parent
                    text: qsTr("暂无任务\n点击“新建”创建任务")
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeNormal
                    horizontalAlignment: Text.AlignHCenter
                }
            }
        }

        // ==================== 底部统计 ====================
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 40
            color: Styles.Theme.backgroundAlternate
            radius: Styles.Theme.radiusSmall

            RowLayout {
                anchors.fill: parent
                anchors.margins: Styles.Theme.spacingSmall
                spacing: Styles.Theme.spacingNormal

                // 总任务数
                ColumnLayout {
                    spacing: 2
                    Layout.fillWidth: true

                    Text {
                        text: taskListModel ? taskListModel.rowCount().toString() : "0"
                        color: Styles.Theme.textPrimary
                        font.pixelSize: 16
                        font.weight: Font.Bold
                    }

                    Text {
                        text: qsTr("总计")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: 9
                    }
                }

                Rectangle {
                    width: 1
                    height: 30
                    color: Styles.Theme.border
                }

                // 成功率
                ColumnLayout {
                    spacing: 2
                    Layout.fillWidth: true

                    Text {
                        text: getSuccessRate()
                        color: Styles.Theme.success
                        font.pixelSize: 16
                        font.weight: Font.Bold
                    }

                    Text {
                        text: qsTr("成功率")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: 9
                    }
                }
            }
        }
    }

    // ==================== 辅助函数 ====================

    function getActiveTaskCount() {
        if (!taskListModel) return 0
        let count = 0
        for (let i = 0; i < taskListModel.rowCount(); i++) {
            let task = taskListModel.getTaskData(i)
            if (task.status === "executing" || task.status === "pending") {
                count++
            }
        }
        return count
    }

    function getSuccessRate() {
        if (!taskListModel || taskListModel.rowCount() === 0) return "-%"

        let completed = 0
        let failed = 0

        for (let i = 0; i < taskListModel.rowCount(); i++) {
            let task = taskListModel.getTaskData(i)
            if (task.status === "completed") completed++
            if (task.status === "failed") failed++
        }

        let total = completed + failed
        if (total === 0) return "-%"

        return Math.round((completed / total) * 100) + "%"
    }
}
